package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	http.HandleFunc("/", rootHandler)
	http.HandleFunc("/healthz", healthHandler)
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	//1. 接收客户端 request，并将 request 中带的 header 写入 response header
	for s, v := range r.Header {
		w.Header().Add(s, v[0])
	}

	//2. 读取当前系统的环境变量中的 VERSION 配置，并写入 response header
	w.Header().Set("Version", os.Getenv("VERSION"))

	//3. server端标准输出客户端IP、HTTP状态码
	hostIP := r.RemoteAddr
	StatusCode := 200
	w.WriteHeader(StatusCode)
	fmt.Println("客户端IP = ", strings.Split(hostIP, ":")[0], "	HTTP返回码 = ", StatusCode)
}

//4. 当访问 localhost/healthz 时，应返回 200
func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
}
